/*
 * Copyright (c) 2006 Your Corporation. All Rights Reserved.
 */

package com.develop.jdbc.jdbc.connection;

import com.develop.jdbc.jdbc.exception.JdbcException;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 描述:	 数据库连接管理
 * 版权:	 Copyright (c) 2005
 * 公司:	 -
 * 作者:	 fenny
 * 版本:	 1.0
 * 创建日期: 2006-10-4
 * 创建时间: 21:32:25
 */

public final class ConnManager {
    private static Configure configure = Configure.getInstance();

    /**
     * 根据datasource.xml文件中配置的数据源ID，得到对应的数据库连接
     *
     * @param id 数据源ID
     * @return conn
     */
    public static Connection getConnection(String id) {
        try {
            DataSource dataSource = configure.getDataSource(id);
            return dataSource.getConnection();
        } catch (SQLException ex) {
            throw new JdbcException(ex);
        }
    }

    /**
     * 获得缺省的数据源的数据库连接
     *
     * @return conn
     */
    public static Connection getConnection() {
        try {
            DataSource dataSource = configure.getDataSource();
            return dataSource.getConnection();
        } catch (SQLException ex) {
            throw new JdbcException(ex);
        }
    }

    /**
     * 开始数据库事务
     *
     * @param conn
     */
    public static void begin(Connection conn) {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.setAutoCommit(false);
            }
        } catch (Exception ex) {
            throw new JdbcException(ex);
        }
    }

    /**
     * 提交数据库事务
     *
     * @param conn
     */
    public static void commit(Connection conn) {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.commit();
            }
        } catch (Exception ex) {
            throw new JdbcException("", ex);
        }
    }

    /**
     * 回滚数据库事务
     *
     * @param conn
     */
    public static void rollback(Connection conn) {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.rollback();
            }
        } catch (Exception ex) {
            throw new JdbcException("", ex);
        }
    }

    /**
     * 关闭数据库连接
     *
     * @param conn
     */
    public static void close(Connection conn) {

        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (Exception ex) {
            throw new JdbcException("", ex);
        }
    }
}
